import React from 'react';
import { TreeSelect } from 'antd';
import projectServer from '../services/project';
import isSuccess from '../utils/error';


const keyObj = {};
function setKey(v) {
    v.title = v.recname;
    v.value = v.recid;
    v.key = v.recid;
}

function getChildren(target, ids) {
    if (target.haschild) {
        target.children = ids[target.recid];
        target.children.forEach(v => {
            setKey(v);
            getChildren(v, ids);
        });
    } else return

}

export default class Select extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            nodes: [],
            value: undefined
        }
    }

    componentWillMount() {
        const { projecttype } = this.props;
        this.getNodes(projecttype, -1); // 获取全部数据
    }

    getNodes = async (projecttype, parentid, name = '') => {
        const res = await projectServer.getCause({ projecttype, parentid, name });
        if (isSuccess(res) && res.data.length) {
            // console.log('---TreeSelect getCause---', res);
            const ids = {};
            res.data.forEach(v => {
                keyObj[v.recname] = v.recid; // 保存
                if (ids[v.parentid]) ids[v.parentid] = [...ids[v.parentid], v];
                else ids[v.parentid] = [v];
            });
            let nodes = ids[0];
            nodes.forEach(v => {
                setKey(v);
                getChildren(v, ids);
            });
            const { value: label } = this.props;
            const value = label ? { label, value: keyObj[label] } : undefined;
            this.setState({ nodes, value });
        }
    }

    onChange = value => {
        this.setState({ value: value || undefined });
        this.props.onChange(value ? value.label : undefined);
    };

    filterTreeNode = (value, treeNode) => {
        return treeNode.props.recname.indexOf(value) > -1;
    }

    render() {
        const { nodes } = this.state;
        return (
            <TreeSelect
                showSearch
                labelInValue
                treeData={nodes}
                value={this.state.value}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                placeholder="请选择案由"
                dropdownMatchSelectWidth
                allowClear
                searchPlaceholder="请输入关键字"
                filterTreeNode={this.filterTreeNode}
                onChange={this.onChange}
            />
        )
    }
}